package priv.books.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import priv.books.pojo.*;
import priv.books.service.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Mr.Zheng
 * @Date 2020/12/10
 * @Description 控制页面的跳转和一些简单逻辑跳转
 */
@Controller
public class SystemController {

    @Autowired
    private BooksTypeService booksTypeService;

    @Autowired
    private BooksService booksService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SaleService saleService;

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 跳转到注册页面
     * @return
     */
    @GetMapping("system/toRegisterPage")
    public String toRegisterPage() {
        return "admin/register";
    }

    /**
     * 跳转到管理员首页
     * @return
     */
    @GetMapping("system/toAdminMainPage")
    public String toAdminMainPage() {
        return "admin/index";
    }

    /**
     * 跳转到用户首页
     * @return
     */
    @GetMapping("system/toUserMainPage")
    public String toUserMainPage() {
        return "admin/index_user";
    }

    /**
     * 后台用户登陆
     * @return
     */
    @PostMapping("system/adminLogin")
    public String verifyLogin(HttpSession session, HttpServletResponse response, String type, String userName, String password) {
        // 判断登录的是管理员还是用户
        if("admin".equals(type)) {
            Admin admin = new Admin();
            admin.setUserName(userName);
            admin.setPassword(SecureUtil.md5(password));
            // 查询验证密码和用户名
            Admin selectResult = adminService.getLoginInfo(admin);
            // 查询结果为空
            if(selectResult == null) {
                // 密码或用户名有误
                session.setAttribute("msg", "登录失败! 用户名或密码输入有误! ");
                return "redirect:/system/toAdminLoginPage";
            } else {
                // 移除消息提示
                session.removeAttribute("msg");
                // 将用户信息保存到session中
                // 设置前将用户密码剔除
                selectResult.setPassword("");
                session.setAttribute("adminUser", selectResult);
                return "redirect:/system/toAdminMainPage";
            }
        } else {
            User user = new User();
            user.setUserName(userName);
            user.setPassword(SecureUtil.md5(password));
            // 查询验证密码和用户名
            User selectResult = userService.getLoginInfo(user);
            // 查询结果为空
            if(selectResult == null) {
                // 密码或用户名有误
                session.setAttribute("msg", "登录失败! 用户名或密码输入有误! ");
                return "redirect:/system/toAdminLoginPage";
            } else {
                // 移除消息提示
                session.removeAttribute("msg");
                // 将用户信息保存到session中
                // 设置前将用户密码剔除
                selectResult.setPassword("");
                session.setAttribute("adminUser", selectResult);
                return "redirect:/system/toUserMainPage";
            }
        }
    }

    /**
     * 退出登录
     * @param session
     * @param response
     * @return
     */
    @GetMapping("/system/adminLoginOut")
    public String loginOut(HttpSession session, HttpServletResponse response) {
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        session.invalidate();
        return "redirect:/system/toAdminLoginPage";
    }

    /**
     * 跳转到欢迎页
     * @return
     */
    @GetMapping("system/toWelcomePage")
    public String toWelcomePage() {
        return "admin/welcome";
    }

    /**
     * 跳转到后台登陆页面
     * @return
     */
    @GetMapping("system/toAdminLoginPage")
    public String toAdminLoginPage() {
        return "admin/login";
    }

    /**
     * 跳转到登录超时页面
     * @return
     */
    @GetMapping("system/toTimeOutPage")
    public String toTimeOutPage() {
        return "admin/error/timeOut";
    }

    /**
     * 新增注册
     * @param userName
     * @param nickName
     * @param password
     * @param type
     * @return
     */
    @PostMapping("system/insertUserInfo")
    @ResponseBody
    public ResultMessage insertUserInfo(String userName, String nickName, String password, String type) {
        if("admin".equals(type)) {
            Admin admin = new Admin();
            admin.setUserName(userName);
            admin.setPassword(SecureUtil.md5(password));
            admin.setNickName(nickName);
            // 新增管理员信息
            boolean save = adminService.save(admin);
            if(save) {
                return new ResultMessage(0, "注册成功！");
            }
            return new ResultMessage(207, "注册失败！");
        } else {
            User user = new User();
            user.setUserName(userName);
            user.setPassword(SecureUtil.md5(password));
            user.setNickName(nickName);
            user.setCreateDate(DateUtil.now());
            // 新增顾客信息
            boolean save = userService.save(user);
            if(save) {
                return new ResultMessage(0, "注册成功！");
            }
            return new ResultMessage(207, "注册失败！");
        }
    }


    // + ---------------------------------------------------------------------------
    // +                           后台管理系统所有页面跳转 Start
    // + ---------------------------------------------------------------------------

    /**
     * 跳转到类型管理页面
     * @param modelAndView
     * @return
     */
    @GetMapping("booksType/toDataPage")
    public ModelAndView toBookTypePage(ModelAndView modelAndView, BooksType booksType) {
        // 查询所有书籍信息
        modelAndView.addObject("booksType", booksTypeService.getAllInfo(booksType));
        modelAndView.addObject("searchInfo", booksType);
        modelAndView.setViewName("admin/booksType/bookTypeList");
        return modelAndView;
    }

    /**
     * 跳转到添加类型页面
     * @param modelAndView
     * @return
     */
    @GetMapping("booksType/toAddPage")
    public ModelAndView toBooksTypeAdd(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/booksType/add");
        return modelAndView;
    }


    /**
     * 跳转到添加管理员页面
     * @param modelAndView
     * @return
     */
    @GetMapping("admin/toAddPage")
    public ModelAndView toAdminAdd(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/user/add");
        return modelAndView;
    }

    /**
     * 跳转到修改管理员
     * @param modelAndView
     * @return
     */
    @GetMapping("admin/toEditPage")
    public ModelAndView toAdminEdit(ModelAndView modelAndView, Integer id) {
        // 查询书籍信息
        modelAndView.addObject("editInfo", adminService.getOne(new QueryWrapper<Admin>().eq("id", id)));
        modelAndView.setViewName("admin/user/edit");
        return modelAndView;
    }



    /**
     * 跳转到修改类型
     * @param modelAndView
     * @return
     */
    @GetMapping("booksType/toEditPage")
    public ModelAndView toBooksTypeEdit(ModelAndView modelAndView, Integer id) {
        // 查询书籍信息
        modelAndView.addObject("editInfo", booksTypeService.getOne(new QueryWrapper<BooksType>().eq("id", id)));
        modelAndView.setViewName("admin/booksType/edit");
        return modelAndView;
    }

    /**
     * 跳转到图书数据展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("books/toDataPage")
    public ModelAndView toBooksPage(ModelAndView modelAndView, Books books) {
        // 查询所有书籍信息
        modelAndView.addObject("books", booksService.getAllInfo(books));
        // 查询所有类型信息
        modelAndView.addObject("typeList", booksTypeService.getAllInfo(null));
        modelAndView.addObject("searchInfo", books);
        modelAndView.setViewName("admin/books/booksList");
        return modelAndView;
    }

    @GetMapping("books/toUserDataPage")
    public ModelAndView toBookUserPage(ModelAndView modelAndView, Books books) {
        // 查询所有书籍信息
        modelAndView.addObject("books", booksService.getAllInfo(books));
        // 查询所有类型信息
        modelAndView.addObject("typeList", booksTypeService.getAllInfo(null));
        modelAndView.addObject("searchInfo", books);
        modelAndView.setViewName("admin/books/booksUserList");
        return modelAndView;
    }

    /**
     * 跳转到图书数据展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("books/toUserBooksPage")
    public ModelAndView toUserBooksPage(ModelAndView modelAndView, Books books) {
        // 查询所有书籍信息
        modelAndView.addObject("books", booksService.getAllInfo(books));
        // 查询所有类型信息
        modelAndView.addObject("typeList", booksTypeService.getAllInfo(null));
        modelAndView.addObject("searchInfo", books);
        modelAndView.setViewName("admin/books/booksUserList");
        return modelAndView;
    }



    /**
     * 跳转到添加图书页面
     * @param modelAndView
     * @return
     */
    @GetMapping("books/toAddPage")
    public ModelAndView toBooksAdd(ModelAndView modelAndView) {
        // 查询所有类型信息
        modelAndView.addObject("typeList", booksTypeService.getAllInfo(null));
        modelAndView.setViewName("admin/books/add");
        return modelAndView;
    }

    /**
     * 跳转到修改图书
     * @param modelAndView
     * @return
     */
    @GetMapping("books/toEditPage")
    public ModelAndView toBooksEdit(ModelAndView modelAndView, Integer id) {
        // 查询所有类型信息
        modelAndView.addObject("typeList", booksTypeService.getAllInfo(null));
        // 查询书籍信息
        modelAndView.addObject("editInfo", booksService.getOne(new QueryWrapper<Books>().eq("id", id)));
        modelAndView.setViewName("admin/books/edit");
        return modelAndView;
    }

    /**
     * 跳转到订单数据展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("order/toDataPage")
    public ModelAndView toOrderPage(ModelAndView modelAndView,Order order) {
        // 查询所有信息
        modelAndView.addObject("orders", orderService.getAllInfo(order));
        modelAndView.addObject("searchInfo", order);
        modelAndView.setViewName("admin/order/orderList");
        return modelAndView;
    }

    /**
     * 跳转到查看订单详情页面
     * @param modelAndView
     * @return
     */
    @GetMapping("order/toFindPage")
    public ModelAndView toOrderAdd(ModelAndView modelAndView, OrderDetail orderDetail) {
        // 调用查询订单详情的方法
        List<OrderDetail> details = orderDetailService.getAllInfo(orderDetail);
        modelAndView.addObject("details", details);
        modelAndView.addObject("searchInfo", orderDetail);
        modelAndView.setViewName("admin/order/find");
        return modelAndView;
    }

    /**
     * 跳转到添加订单页面
     * @param modelAndView
     * @return
     */
    @GetMapping("order/toAddPage")
    public ModelAndView toOrderAdd(ModelAndView modelAndView,Books books) {
        // 查询所有类型信息
        modelAndView.addObject("books", booksService.getAllInfo(books));
        modelAndView.setViewName("admin/order/add");
        return modelAndView;
    }

    /**
     * 跳转到添加订单页面
     * @param modelAndView
     * @return
     */
    @GetMapping("order/toInputNumPage")
    public ModelAndView toInputNumPage(ModelAndView modelAndView, String ids) {
        // 查询所有类型信息
        modelAndView.addObject("books", booksService.getByIds(ids));
        modelAndView.setViewName("admin/order/inputNum");
        return modelAndView;
    }

    /**
     * 跳转到销售数据展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("sale/toDataPage")
    public ModelAndView toSalePage(ModelAndView modelAndView, Sale sale) {
        // 查询所有信息
        List<Sale> saleInfos = saleService.getAllInfo(sale);
        // 统计销量和销售金额
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("price", saleInfos.stream().map(Sale::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        dataMap.put("totalNum", saleInfos.stream().mapToInt(Sale::getSaleNum).sum());
        modelAndView.addObject("sales", saleInfos);
        modelAndView.addObject("dataMap", dataMap);
        modelAndView.addObject("searchInfo", sale);
        modelAndView.setViewName("admin/sale/saleList");
        return modelAndView;
    }

    /**
     * 跳转到销量前五书籍展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("sale/toBooksDataPage")
    public ModelAndView toBooksSalePage(ModelAndView modelAndView, Sale sale) {
        // 查询所有信息
        List<Map<String, Object>> saleInfos = saleService.getBooksSale(sale);
        modelAndView.addObject("sales", saleInfos);
        modelAndView.addObject("searchInfo", sale);
        modelAndView.setViewName("admin/sale/saleBookList");
        return modelAndView;
    }

    /**
     * 跳转到销售数据展示页
     * @param modelAndView
     * @return
     */
    @GetMapping("admin/toDataPage")
    public ModelAndView toAdminPage(ModelAndView modelAndView, Admin admin) {
        modelAndView.addObject("adminList", adminService.getAllInfo(admin));
        modelAndView.addObject("searchInfo", admin);
        modelAndView.setViewName("admin/user/adminList");
        return modelAndView;
    }

    @GetMapping("admin/toUserDataPage")
    public ModelAndView toUserPage(ModelAndView modelAndView, User user) {
        modelAndView.addObject("userList", userService.getAllInfo(user));
        modelAndView.addObject("searchInfo", user);
        modelAndView.setViewName("admin/user/userList");
        return modelAndView;
    }



    // + ---------------------------------------------------------------------------
    // +                           后台管理系统所有页面跳转 End
    // + ---------------------------------------------------------------------------

}
